#include <unistd.h>
#include <signal.h>


#include <iostream>

using std::cout;
using std::endl;

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/RedisMessage.h>

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig number %d is comming\n", num);
    waitGroup.done();
}

void test0()
{
    signal(SIGINT, sighandler);
    int * pnumber = new int(100);
    std::string url = "redis://127.0.0.1:6379";
    auto redisTask = WFTaskFactory::create_redis_task(url, 1, 
        [pnumber](WFRedisTask * redistask){
            cout << "redisCallback1 is running" << endl;
            cout << "pnumber:" << pnumber << endl;
            cout << "*pnumber:" << *pnumber << endl;

            //1. 错误的检测
            int state = redistask->get_state();
            int error = redistask->get_error();

            switch(state) {
            case WFT_STATE_SYS_ERROR:
                printf("system error: %s\n", strerror(error)); break;
            case WFT_STATE_DNS_ERROR:
                printf("dns error: %s\n", gai_strerror(error)); break;
            case WFT_STATE_SUCCESS:
                break;
            }

            if(state != WFT_STATE_SUCCESS) {
                printf("error occurs!\n");
                return;
            }

            printf("task success\n");
            //2. 获取请求信息
            auto req = redistask->get_req();
            std::string command;
            std::vector<std::string> params;
            req->get_command(command);
            req->get_params(params);
            cout << command << " ";
            for(auto & param : params) {
                cout << param << " ";
            }
            cout << endl;

            //3. 获取响应信息
            auto resp = redistask->get_resp();
            protocol::RedisValue result;
            resp->get_result(result);

            //遍历RedisValue的数据
            if(result.is_string()) {
                cout << "value is string, value:"
                     << result.string_value() << endl;
            } else if(result.is_array()) {
                cout << "value is array:" << endl;
                for(size_t i = 0; i < result.arr_size(); ++i) {
                    cout << "arr[" << i << "]:" 
                         << result.arr_at(i).string_value() << endl;
                }
            }
        });
    auto req = redisTask->get_req();
    req->set_request("HSET", {"student", "name", "Jackie", "age", "30"});
    redisTask->start();
    waitGroup.wait();

    if(pnumber) {
        delete pnumber; 
        pnumber = nullptr;
    }   
}


int main()
{
    test0();
    return 0;
}

